package com.yls.except.util;

import java.util.HashMap;
import java.util.Map;

public class Distance {
	private static final double EARTH_RADIUS = 6378137;
	
	private static double rad(double d)
	     {
	        return d * Math.PI / 180.0;
	     }
	     
	     /**
	      * 根据两点间经纬度坐标（double值），计算两点间距离，单位为米
	      * @param lng1
	      * @param lat1
	      * @param lng2
	      * @param lat2
	      * @return
	      */
	     public static double GetDistance(double lng1, double lat1, double lng2, double lat2)
	     {
	        double radLat1 = rad(lat1);
	        double radLat2 = rad(lat2);
	        double a = radLat1 - radLat2;
	        double b = rad(lng1) - rad(lng2);
	        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + 
	         Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	        s = s * EARTH_RADIUS;
	        s = Math.round(s * 10000) / 10000;
	        return s;
	     }
	     
	     
	     
	     
	     /**
	      * 计算经纬度点对应正方形4个点的坐标    距离单位（米）
	      *
	      * @param longitude
	      * @param latitude
	      * @param distance
	      * @return
	      */
	     public static Map<String, double[]> GetSquarePoint(double longitude,
	             double latitude, double distance) {
	         Map<String, double[]> squareMap = new HashMap<String, double[]>();
	         // 计算经度弧度,从弧度转换为角度
	         double dLongitude = 2 * (Math.asin(Math.sin(distance
	                 / (2 * EARTH_RADIUS))
	                 / Math.cos(Math.toRadians(latitude))));
	         dLongitude = Math.toDegrees(dLongitude);
	         // 计算纬度角度
	         double dLatitude = distance / EARTH_RADIUS;
	         dLatitude = Math.toDegrees(dLatitude);
	         // 正方形
	         double[] leftTopPoint = { latitude + dLatitude, longitude - dLongitude };
	         double[] rightTopPoint = { latitude + dLatitude, longitude + dLongitude };
	         double[] leftBottomPoint = { latitude - dLatitude,
	                 longitude - dLongitude };
	         double[] rightBottomPoint = { latitude - dLatitude,
	                 longitude + dLongitude };
	         squareMap.put("leftTopPoint", leftTopPoint);
	         squareMap.put("rightTopPoint", rightTopPoint);
	         squareMap.put("leftBottomPoint", leftBottomPoint);
	         squareMap.put("rightBottomPoint", rightBottomPoint);
	         return squareMap;
	     }

	     /**
	      * @param args
	      */
	     public static void main(String[] args)
	     {
	         double distance1 = GetDistance(121.491909,31.233234,121.411994,31.206134);
	    	 double distance = GetDistance(106.47922495185,29.53301405380,106.48330233063,29.52061537736);
	         System.out.println(distance1+"Distance is:"+distance);
	         
	     }


}
